package com.example.maoyanmovie.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import com.example.maoyanmovie.databinding.ActivitySeatSelectionBinding;
import com.example.maoyanmovie.model.Movie;
import com.example.maoyanmovie.model.OrderInfo;
import com.example.maoyanmovie.model.Seat;
import com.example.maoyanmovie.ui.adapter.SeatAdapter;
import com.example.maoyanmovie.utils.Constants;
import com.example.maoyanmovie.utils.ToastUtils;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Random;

public class SeatSelectionActivity extends AppCompatActivity {

    private ActivitySeatSelectionBinding binding;
    private SeatAdapter seatAdapter;
    private List<Seat> seatList = new ArrayList<>();
    private List<Seat> selectedSeats = new ArrayList<>();
    private Movie movie;

    private static final int ROWS = 10;        // 10排
    private static final int COLUMNS = 11;     // 每排11个座位（含行号列）
    private static final double SEAT_PRICE = 50.0;  // 每个座位50元
    private static final int MAX_SELECTED = 5;       // 最多选5个座位

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivitySeatSelectionBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        // 获取传递的电影信息
        movie = (Movie) getIntent().getSerializableExtra(Constants.INTENT_KEY_MOVIE);

        initView();
        initSeats();
    }

    private void initView() {
        binding.ivBack.setOnClickListener(v -> finish());

        // 设置GridLayoutManager，列数为11（1列行号 + 10列座位）
        GridLayoutManager layoutManager = new GridLayoutManager(this, COLUMNS);
        binding.recyclerViewSeats.setLayoutManager(layoutManager);

        // 设置Adapter
        seatAdapter = new SeatAdapter(this, COLUMNS);
        binding.recyclerViewSeats.setAdapter(seatAdapter);

        // 设置座位点击监听
        seatAdapter.setOnSeatClickListener((seat, position) -> {
            if (seat.getStatus() == Seat.STATUS_AVAILABLE) {
                // 检查是否超过最大选择数量
                if (selectedSeats.size() >= MAX_SELECTED) {
                    ToastUtils.showShort(this, "最多只能选择" + MAX_SELECTED + "个座位");
                    return;
                }
                // 标记为已选
                seat.setStatus(Seat.STATUS_SELECTED);
                selectedSeats.add(seat);
            } else if (seat.getStatus() == Seat.STATUS_SELECTED) {
                // 取消选择
                seat.setStatus(Seat.STATUS_AVAILABLE);
                selectedSeats.remove(seat);
            }

            seatAdapter.notifyItemChanged(position);
            updateSelectedInfo();
        });

        // 确认选座按钮
        binding.btnConfirm.setOnClickListener(v -> {
            if (selectedSeats.isEmpty()) {
                ToastUtils.showShort(this, "请先选择座位");
                return;
            }

            // 创建订单信息
            OrderInfo orderInfo = createOrderInfo();

            // 跳转到订单确认页面
            Intent intent = new Intent(this, OrderConfirmActivity.class);
            intent.putExtra(Constants.INTENT_KEY_ORDER_INFO, orderInfo);
            startActivity(intent);
        });
    }

    private void initSeats() {
        seatList.clear();
        Random random = new Random();

        // 生成座位数据
        for (int row = 0; row < ROWS; row++) {
            for (int col = 0; col < COLUMNS; col++) {
                if (col == 0) {
                    // 第一列用于显示行号，不是真实座位
                    seatList.add(new Seat(row, col, Seat.STATUS_AVAILABLE, 0));
                } else {
                    // 随机生成一些已售座位（约20%的座位）
                    int status = random.nextInt(100) < 20 ? Seat.STATUS_SOLD : Seat.STATUS_AVAILABLE;
                    seatList.add(new Seat(row, col - 1, status, SEAT_PRICE));
                }
            }
        }

        seatAdapter.setSeatList(seatList);
        updateSelectedInfo();
    }

    private void updateSelectedInfo() {
        if (selectedSeats.isEmpty()) {
            binding.tvSelectedSeats.setText("已选座位：无");
            binding.tvTotalPrice.setText("总价：¥0");
        } else {
            StringBuilder sb = new StringBuilder("已选座位：");
            double totalPrice = 0;

            for (int i = 0; i < selectedSeats.size(); i++) {
                Seat seat = selectedSeats.get(i);
                sb.append(seat.getSeatName());
                if (i < selectedSeats.size() - 1) {
                    sb.append(", ");
                }
                totalPrice += seat.getPrice();
            }

            binding.tvSelectedSeats.setText(sb.toString());
            binding.tvTotalPrice.setText(String.format("总价：¥%.0f", totalPrice));
        }
    }

    private OrderInfo createOrderInfo() {
        // 收集座位名称
        List<String> seatNames = new ArrayList<>();
        double totalPrice = 0;
        for (Seat seat : selectedSeats) {
            seatNames.add(seat.getSeatName());
            totalPrice += seat.getPrice();
        }

        // 电影名称
        String movieName = movie != null ? movie.getName() : "未知电影";

        // 影院名称（模拟，可以从电影详情传递）
        String cinemaName = "万达影城";

        // 放映时间（模拟，生成当前时间+2小时）
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.CHINA);
        long currentTime = System.currentTimeMillis() + 2 * 60 * 60 * 1000; // 当前时间+2小时
        String showTime = sdf.format(new Date(currentTime));

        return new OrderInfo(movieName, cinemaName, showTime, seatNames, totalPrice);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        binding = null;
    }
}
